package ping.client;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 客户端
 */
public class Client extends Thread {
	private ClientSocket client;
	private byte[] requestBuffer;
	private byte[] replyBuffer;
	private DatagramPacket requestPacket;
	private DatagramPacket replyPacket;
	private ReceivePackets receivePackets = null;
	private DatagramSocket socket;
	
	public Client(ClientSocket client) {
		// TODO Auto-generated constructor stub
		this.client = client;
	}
	
	private ReceivePackets client() {
		// TODO Auto-generated method stub	
		long[] ttls = new long[10];
		int received = 0;
		String receive = null, send = null;
		try {
			socket = new DatagramSocket(); // 创建DatagramSocket
			for (int i = 1; i <= 10; i++) { 
				send = ClientSocket.getData(i);
				requestBuffer = send.getBytes();
				replyBuffer = new byte[requestBuffer.length];
				// 创建请求包
				requestPacket = new DatagramPacket(
					requestBuffer, 
					requestBuffer.length, 
					client.getAddress(),
					client.getPort()
				);
				replyPacket = new DatagramPacket(replyBuffer, replyBuffer.length); 
				try {
					long sendTime = System.currentTimeMillis();
					socket.send(requestPacket);	// 发送请求包
					socket.setSoTimeout(1000);  // 设置超时时间为1秒
					long replyTime;
					do { // 不断接收应答包直到应答包的内容与请求包的内容匹配
						socket.receive(replyPacket);
						receive = new String(replyPacket.getData());
					} while (!send.equals(receive));
					replyTime = System.currentTimeMillis();
					long time = replyTime - sendTime; // 计算接收时间
					System.out.println("Received packet, ttl=" + time + "ms");
					ttls[i - 1] = time; // 将当次的接收时间记录到数组中
					received++; // 接收包数目加一
				} catch (IOException e) {
					// TODO: handle exception
					System.err.println(e.getMessage());
					ttls[i - 1] = -1; 
				} 
			}
			receivePackets = new ReceivePackets(new TimeToLive(ttls), received, 10 - received, 10);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		return receivePackets;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		ReceivePackets receivePackets = client();
		if (receivePackets != null) {
			TimeToLive ttl = receivePackets.getTimeToLive();
			System.out.println("--- " + client.getAddress() + " ping statistics ---");
			System.out.println("10 packets transmitted, " + receivePackets.getReceived() + " received, "
					+ receivePackets.getLost() + " packets lost");
			System.out.println("ttl min/avg/max = " + ttl.minTtl() + "/" + ttl.ttlAverage() + "/"
					+ ttl.maxTtl() + " ms");
		}
	}
}